import {app, BrowserWindow, ipcMain, shell,screen} from 'electron'
import {electronApp, is, optimizer} from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { createManagePlugin, updateManageWindow } from "./managePlugin";
import path, {join} from 'path'
import { clearCache, createSecondaryWindow, loadUrl } from "./second";

const deskAppTest = false,//测试收银客户端标志
  mainWindowUrl = 'http://client.smartorderkiosk.com/desk/#/login'

//创建主屏页面
function createWindow(): BrowserWindow {
  console.log("createWindow==")
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1200,
    minWidth: 1200,
    height: 608,
    minHeight: 608,
    show: false,
    autoHideMenuBar: true,//隐藏menu操作栏
    titleBarStyle: 'hidden',//隐藏title标题栏
    frame: false, // 移除默认的标题栏
    title: "本地项目管理客户端",
    icon: icon,
    // titleBarStyle: app.isPackaged ? 'hidden' : '',
    webPreferences: {
      webSecurity: false,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: true
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.on("resize", (e) => {
    let sizeData = mainWindow.getContentBounds()
    console.log("sizeData", sizeData)
    let {width, height} = sizeData
    let zoomWidth = width / 1066
    let zoomHeight = height / 571
    let zoomFactor = Math.min(zoomWidth, zoomHeight)
    console.log("sizeData====",zoomFactor)
    mainWindow.webContents.send('zoomFactor', zoomFactor);
  })

  mainWindow.on('closed', (e) => {
    console.log("closed====")
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return {action: 'deny'}
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    if (deskAppTest) loadUrl(mainWindow, mainWindowUrl)
    else mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  // mainWindow.webContents.openDevTools({  });
  ipcMain.on("open-dev-tool",   (event, arg) => {
    console.log("get arg:", arg);
    if (arg) {
      if (arg.open) {
        mainWindow.webContents.openDevTools({mode: "detach", activate: false});
      } else {
        mainWindow.webContents.closeDevTools();
      }
    }
  });
  clearCache(mainWindow)
  if (deskAppTest) createSecondaryWindow()
  return mainWindow
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  console.log("app-whenReady==")
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  let mainWindow= createWindow()

  //创建ManagePlugin对象时需要传入mainWindow使用
  createManagePlugin(mainWindow)

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    console.log("activate==",BrowserWindow.getAllWindows(),mainWindow);
    if (BrowserWindow.getAllWindows().length === 0) updateManageWindow(createWindow())
  })
})
app.commandLine.appendSwitch('ignore-certificate-errors')

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
